<template>
  <div class="page-container">
    <el-row :gutter="20">
      <!--店铺-->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
              <span>所属店铺：</span>
              <el-select v-model="filters.shop_id" @change="shopIdChange" placeholder="所属店铺" style="width: 60%">
                <el-option label="--- 请选择商铺 ---" value=""></el-option>
                <el-option
                  v-for="item in optionShop"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
          </div>
          <div style="height: 550px; overflow-y:auto;">
            <el-tree :data="treeData"
                     :props="defaultProps"
                     @node-click="handleNodeClick">
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <!-- 店铺列表-->
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
              <kt-button
                style="float: right;"
                size ="medium"
                icon="fa fa-plus"
                :label="$t('action.add')"
                type="primary"
                @click="handleAdd"/>
          </div>
          <div style="height: 550px;">
            <!--表格栏-->
            <el-table
              :data="table.content"
              :header-cell-style="{ 'color': '#FFF','background-color': '#2F4554'}"
              :show-overflow-tooltip="table.showOverflowTooltip"
              max-height="550px"
              :size="table.size"
              :align="table.align"
              style="width:100%;">

              <template v-for="column in filterColumns">
                <el-table-column
                  header-align="center"
                  align="center"
                  :prop="column.prop"
                  :label="column.label"
                  :width="column.width"
                  :min-width="column.minWidth"
                  :fixed="column.fixed"
                  :key="column.prop"
                  :type="column.type"
                  :formatter="column.formatter"
                  :sortable="column.sortable==null?true:column.sortable">
                  <template slot-scope="scope">
                    <template v-if="!column.render">
                      <template v-if="column.formatter">
                        <div v-html="column.formatter(scope.row, column,scope.row[column.prop],scope.index)"></div>
                      </template>
                      <template v-else>
                        <span>{{scope.row[column.prop]}}</span>
                      </template>
                    </template>
                    <template v-else>
                      <expand-dom
                        :column="column"
                        :row="scope.row"
                        :render="column.render"
                        :index="index"></expand-dom>
                    </template>
                  </template>
                </el-table-column>
              </template>

              <el-table-column
                :label="$t('action.operation')"
                width="185"
                fixed="right"
                header-align="center"
                align="center">
                <template slot-scope="scope">
                  <kt-button
                    icon="fa fa-edit"
                    :label="$t('action.edit')"
                    :size="size"
                    @click="handleEdit(scope)"/>
                  <kt-button
                    icon="fa fa-trash"
                    :label="$t('action.delete')"
                    :size="size"
                    type="danger"
                    @click="handleDelete(scope.row)"/>
                </template>
              </el-table-column>
            </el-table>
            <!--分页栏-->
            <div class="toolbar" style="padding:10px;">
              <el-pagination
                layout="total, prev, pager, next, jumper,sizes"
                @current-change="refreshPageRequest"
                :current-page="table.pageRequest.pageNum"
                :page-size="table.pageRequest.pageSize"
                :total="table.totalSize"
                style="float:right;"
                :page-sizes="[10, 20, 30, 40]"
                @size-change="handleSizeChange"/>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="40%"
      :visible.sync="editDialogVisible"
      :close-on-click-modal="false">
      <el-form
        :model="dataForm"
        label-width="80px"
        :rules="dataFormRules"
        ref="dataForm"
        :size="size">
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="parent_id">
          <el-select v-model="dataForm.parent_id" style="width: 100%">
            <el-option
              v-for="item in optionType"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="text">
          <el-input v-model="dataForm.text" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所属店铺" prop="shop_id">
          <el-select v-model="dataForm.shop_id" style="width: 100%">
            <el-option
              v-for="item in optionShop"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别介绍" prop="describes">
          <el-input v-model="dataForm.describes" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortno">
          <el-input-number v-model="dataForm.sortno":min="1" style="width: 30%"></el-input-number>
        </el-form-item>
        <el-form-item label="logo" prop="pic">
          <el-upload
            ref="my-upload"
            class="avatar-uploader"
            :action="imgUrl"
            :show-file-list="false"
            :on-success="logohandleAvatarSuccess">
            <img v-if="dataForm.pic" :src="dataForm.pic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="editDialogVisible = false" @click="clearFiles">{{$t('action.cancel')}}</el-button>
        <el-button
          :size="size"
          type="primary"
          @click.native="submitForm"
          :loading="editLoading">{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import CyTable from "@/views/Core/CyTable";
  import KtButton from "@/views/Core/KtButton";
  import { format, formatDate } from "@/utils/datetime";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
  export default {
    components: {
      KtButton,
      CyTable,
      TableColumnFilterDialog
    },
    data() {
      return {
        size: "small",
        filters: {
          shop_id: "",
          t: "productType"
        },
        optionShop: [],
        optionType: [],
        table: {
          showOverflowTooltip: true,
          size: "mini",
          align: "left",
          totalSize: 0,
          content: [],
          // 分页信息
          pageRequest: {
            pageNum: 1,
            pageSize: 10
          },
        },
        filterColumns: [],
        columns: [
          {prop: "id", label: "序号", minWidth: 50},
          {prop: "text", label: "分类名称", minWidth: 120},
          {prop: "ptext", label: "父级分类", minWidth: 120, formatter:function (row, column, prop) {
            if(prop == undefined){
                return "-"
              } else {
                return prop
              }
            }},
          {prop: "sname", label: "所属店铺", minWidth: 120},
        ],
        editLoading: false,
        operation: false, // true:新增, false:编辑
        editDialogVisible: false, // 新增编辑界面是否显示
        dataFormRules: {
          text: [{required: true, message: "请输入分类名称", trigger: "blur"}],
          shop_id: [{required: true, message: "请输入所属店铺", trigger: "blur"}],
          parent_id: [{required: true, message: "请输入所属分类", trigger: "blur"}],
          describes: [{required: true, message: "请输入类别介绍", trigger: "blur"}],
          sortno: [{required: true, message: "请输入排序", trigger: "blur"}]
        },
        // 新增编辑界面数据
        dataForm: {
          id: "",
          parent_id: "",
          text: "",
          describes: "",
          sortno: "",
          pic: ""
        },
        // 店铺树形
        treeData: [],
        defaultProps: {
          children: "nodes",
          label: "text"
        },
        // logo上传
        imgUrl:this.utils.imgUploadUrl,
        dialogVisible: false
      };
    },
    mounted() {
      this.initColumns();
      this.queryTypeList();
    },
    methods: {
      // 下拉框店铺和商品分类
      queryTypeList() {
        let this_ = this;
        this.utils.request.queryShop(null, function (res) {
          this_.optionShop = res.data;
        });

        this.utils.request.queryProductType({t: "productType"}, function (res) {
          this_.optionType = res.data;
        });
      },
      // 换页刷新
      refreshPageRequest: function(pageNum) {
        this.table.pageRequest.pageNum = pageNum;
        this.findPage();
      },
      // 换页刷新
      handleSizeChange: function(pageSize) {
        this.table.pageRequest.pageSize = pageSize;
        this.table.pageRequest.pageNum = 1;
        this.findPage();
      },
      // 获取分页数据
      findPage: function(data) {
        var this_ = this;
        this.filters.start = this.table.pageRequest.pageNum;
        this.filters.limit = this.table.pageRequest.pageSize;
        this.utils.request.queryUserPage(this.filters, function(res) {
          if (res.rows == null) {
            res.rows = [];
          }
          this_.table.content = res.rows;
          this_.table.totalSize = Number(res.total);
        });
      },
      // 动态所属店铺和商品分类列表下拉查询
      shopIdChange() {
        let this_ = this;
        // 店铺列表
        this_.utils.request.queryAllProductType({shop_id: this_.filters.shop_id} , function (res) {
          this_.treeData = res.data;
        });
       // 分类列表
        this_.findPage();
      },
      // tree点击事件
      handleNodeClick(treeData) {
        let this_ = this;
        let arr = {
          id: treeData.id,
          shop_id: treeData.shop_id,
          t: "productType"
        };
        this.utils.request.queryProductType(arr, function(res) {
          this_.table.content = res.data;
          this_.table.totalSize = Number(res.total);
        });

      },
      // 单行删除
      handleDelete: function (row) {
        let ids = row.id;
        this.delete(ids);
      },
      delete: function(ids) {
        var params = {};
        params.t = "productType";
        params.ids = ids;
        var this_ = this;
        this.utils.request.deleteUserInfo(params, function(res) {
          if (res.code == "0000") {
            this_.$message({ message: "操作成功", type: "success" });
            this_.findPage(null);
            this_.shopIdChange();
          } else {
            this_.$message({ message: "操作失败, " + res.msg, type: "error" });
          }
        });
      },
      // 显示新增界面
      handleAdd: function() {
        this.editDialogVisible = true;
        this.operation = true;
        if (this.dataForm.id != '') {
          this.dataForm.creator = "";
          this.dataForm.create_time = "";
          this.dataForm.pic = "";
          this.dataForm.leaf = "";
          this.dataForm.describes = "";
          this.dataForm.is_delete = "";
          this.dataForm.sortno = "";
          this.dataForm.shop_id = "";
          this.dataForm.update_time = "";
          this.dataForm.parent_id = "";
          this.dataForm.sname = "";
          this.dataForm.updator = "";
          this.dataForm.id = "";
          this.dataForm.text = "";
          this.dataForm.status = "";
        }
      },
      // 显示编辑界面
      handleEdit: function(params) {
        if (0 === params.row.parent_id) {
          params.row.parent_id = "";
        }
        this.editDialogVisible = true;
        this.operation = false;
        this.$nextTick(function() {
          this.dataForm = Object.assign({}, params.row);
        });
      },
      // 编辑
      submitForm: function() {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              let params = Object.assign({}, this.dataForm);
              params.t = "productType";
              var this_ = this;
              this.utils.request.editInfo(params, function(res) {
                if (res.code == "0000") {
                  this_.$message({ message: "操作成功", type: "success" });
                  this_.$refs["dataForm"].resetFields();
                  this_.editDialogVisible = false;
                  this_.findPage(null);
                  this_.shopIdChange();
                } else {
                  this_.$message({
                    message: "操作失败, " + res.msg,
                    type: "error"
                  });
                }
              });
            });
          }
        });
      },
      // 时间格式化
      dateFormat: function(row, column, cellValue, index) {
        return format(row[column.property]);
      },
      // 处理表格列过滤显示
      initColumns: function () {
        var temp = [];
        $.each(this.columns, function (key, val) {
          temp.push(val)
        })
        this.filterColumns = temp;
        this.findPage();
      },
      // logo上传
      logohandleAvatarSuccess(res, file) {
        this.dataForm.pic = res.data.imgUrl;
      },
      clearFiles () {
        this.$refs['my-upload'].clearFiles();
      }
    }
  };
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #2F4554;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .text {
    font-size: 20px;
  }
  .item {
    margin-bottom: 18px;
  }
  .clearfix:before,
   .clearfix:after {
     display: table;
     content: "";
   }
  .clearfix:after {
    clear: both
  }

  .box-card {
    min-height: 500px;
  }

</style>
